package Presentacion;

import AccesoDatos.Comando;
import AccesoDatos.Conexion;
import LogicaNegocio.Deuda;
import LogicaNegocio.Deudor;
import LogicaNegocio.Telefono;
import Presentacion.frmGestionCobro;
import java.awt.Dimension;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author CR
 */
public class frmCobro extends javax.swing.JInternalFrame {

    Conexion conexion = null;
    
    public frmCobro(Conexion Pconexion) {
        conexion = Pconexion;
        initComponents();
        cargarTbDeudores(); //Carga el JTable con los deudores 
        tbDeudores.getColumnModel().getColumn(0).setPreferredWidth(15);
        tbDeudores.getColumnModel().getColumn(1).setPreferredWidth(120);
        tbDeudores.getColumnModel().getColumn(2).setPreferredWidth(15);
       
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        rbgFrecuenciaPago = new javax.swing.ButtonGroup();
        jLabel1 = new javax.swing.JLabel();
        txtCedula = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txtNombre = new javax.swing.JTextField();
        btnBuscar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbDeudores = new javax.swing.JTable();
        jComboBox1 = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();

        setClosable(true);
        setIconifiable(true);
        setTitle("Cobro");
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel1.setText("Cédula:");

        txtCedula.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel2.setText("Nombre:");

        txtNombre.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N

        btnBuscar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        btnBuscar.setText("Buscar");

        tbDeudores.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        tbDeudores.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tbDeudoresMouseClicked(evt);
            }
            public void mousePressed(java.awt.event.MouseEvent evt) {
                tbDeudoresMousePressed(evt);
            }
        });
        jScrollPane1.setViewportView(tbDeudores);

        jComboBox1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Todos", "Gestión diaria", "Promesas de pago" }));

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel3.setText("Ordenar por:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 577, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                            .addGap(36, 36, 36)
                            .addComponent(jLabel1)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(txtCedula, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(jLabel2)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(66, 66, 66)
                            .addComponent(btnBuscar))))
                .addContainerGap(35, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(34, 34, 34)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtCedula, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnBuscar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(9, 9, 9)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 254, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(61, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void tbDeudoresMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbDeudoresMouseClicked
         seleccion();
    }//GEN-LAST:event_tbDeudoresMouseClicked

    private void tbDeudoresMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbDeudoresMousePressed
        seleccion();
    }//GEN-LAST:event_tbDeudoresMousePressed
    
    private void cargarTbDeudores(){
        DefaultTableModel modelo = new DefaultTableModel();
        modelo.addColumn("Cédula");
        modelo.addColumn("Nombre");
        modelo.addColumn("Número de operación");
        tbDeudores.setModel(modelo);
        try{
                Comando comando = new Comando("SELECT tb_deuda.Id_Deudor, tb_deudor.Nombre, tb_deuda.Id_Deuda FROM tb_deuda, tb_deudor WHERE tb_deuda.Id_Deudor = tb_deudor.Id_Deudor");
                ResultSet rs = comando.ejecutarSQL(conexion); 
                while (rs.next())
                {
       // Se crea un array que será una de las filas de la tabla.
                Object [] fila = new Object[3]; // Hay cuatro columnas en la tabla

       // Se rellena cada posición del array con una de las columnas de la tabla en base de datos.
                for (int i=0;i<3;i++)
                    fila[i] = rs.getObject(i+1); // El primer indice en rs es el 1, no el cero, por eso se suma 1.
                    
       // Se añade al modelo la fila completa.
                modelo.addRow(fila);
                }
            }catch(Exception ex){
                JOptionPane.showMessageDialog(null, ex.getMessage(), null, JOptionPane.ERROR_MESSAGE);
            }    
    }
        private void seleccion(){
//            frmGestionCobro fGestionCobro = new frmGestionCobro(conexion);
//            frmMain.jDesktopPane1.add(fGestionCobro);
//            this.dispose();
//            fGestionCobro.show();
        try{
            int row=tbDeudores.getSelectedRow();
            Comando comando = new Comando("SELECT * FROM tb_deuda, tb_deudor WHERE tb_deuda.Id_Deudor = '"+ tbDeudores.getValueAt(row, 0) +"' AND tb_deudor.Id_Deudor = '"+ tbDeudores.getValueAt(row, 0) +"'"); // Consulta que obtiene la informacion de la deuda seleccionada en el jtable
            ResultSet rs = comando.ejecutarSQL(conexion);
            rs.next();
            Deudor deudor=new Deudor();
            Deuda deuda=new Deuda();
            deuda.setId_Deuda(rs.getInt("Id_Deuda"));
            deuda.setId_Cartera(rs.getInt("Id_Cartera"));
            deuda.setId_Usuario(rs.getInt("Id_Usuario"));
            deuda.setProducto(rs.getString("Producto"));
            deuda.setDias_Mora(rs.getInt("Dias_Mora"));
            deuda.setCategoria(rs.getString("Categoria"));
            deuda.setCapital_Adeudado(rs.getDouble("Capital_Adeudado"));
            deuda.setCuota(rs.getDouble("Cuota"));
            deuda.setSaldo_Colones(rs.getDouble("Saldo_Colones"));
            deuda.setSaldo_Dolares(rs.getDouble("Saldo_Dolares"));
            deuda.setTotal_Adeudado_Colones(rs.getDouble("Total_Adeudado_Colones"));
            deuda.setTotal_Adeudado_Dolares(rs.getDouble("Total_Adeudado_Dolares"));
            deuda.setSaldo_Mora_Colones(rs.getDouble("Saldo_Mora_Colones"));
            deuda.setSaldo_Mora_Dolares(rs.getDouble("Saldo_Mora_Dolares"));
            deuda.setPago_Minimo_Colones(rs.getDouble("Pago_Minimo_Colones"));
            deuda.setPago_Minimo_Dolares(rs.getDouble("Pago_Minimo_Dolares"));
            String FechaUP = new SimpleDateFormat("dd/MM/yyyy").format(rs.getDate("Fecha_Ultimo_Pago")); // Convierte la Fecha del ultimo pago de Date a String
            deuda.setFecha_Ultimo_Pago(FechaUP);
            String FechaPP = new SimpleDateFormat("dd/MM/yyyy").format(rs.getDate("Fecha_Proximo_Pago")); // Convierte la Fecha del proximo pago de Date a String
            deuda.setFecha_Proximo_Pago(FechaPP);
            deuda.setMonto_Pago(rs.getDouble("Monto_Pago"));
            //Creamos el deudor al que esta vinculado la deuda
            deudor.setId_Deudor(rs.getLong("Id_Deudor"));
            deudor.setvTelefonos(obtenerTelefonos(String.valueOf(deudor.getId_Deudor())));
            if(rs.getObject("Id_Info_Contacto") == null){
                deudor.setId_Info_Contacto(0);
            }else{
            deudor.setId_Info_Contacto(rs.getLong("Id_Info_Contacto"));
            }       
            deudor.setNombre(rs.getString("Nombre"));
            
            deuda.setDeudor(deudor);  // Asignamos el deudor al que pertenece la deuda seleccionada en el JTable
            
            frmGestionCobro fGestionCobro = new frmGestionCobro(conexion, deuda);            
            Dimension desktopSize = frmMain.jDesktopPane1.getSize();
            Dimension jInternalFrameSize = fGestionCobro.getSize();
            int width = (desktopSize.width - jInternalFrameSize.width) / 2;
            int height = (desktopSize.height - jInternalFrameSize.height) / 2;
            fGestionCobro.setLocation(width, height);
            frmMain.jDesktopPane1.add(fGestionCobro);
            fGestionCobro.show();
        
        }catch(Exception ex){
            JOptionPane.showMessageDialog(null, ex.getMessage(), null, JOptionPane.ERROR_MESSAGE);
        }
    }
        
     private ArrayList <Telefono> obtenerTelefonos(String cedula){   // Metodo que obtiene los telefonos asociados a una cedula
        
        ArrayList <Telefono> vTelefonos = new ArrayList <Telefono>();
    
        try{                    
                    
                    Comando comando = new Comando("SELECT * FROM tb_telefonos_ice WHERE CEDULA='"+ cedula +"'");
                    ResultSet rs = comando.ejecutarSQL(conexion);
                    if(rs.next()){
                        rs.beforeFirst();                        
                        
                        while (rs.next())
                        {       
                            Telefono telefono = new Telefono();
                            telefono.setTEL(rs.getDouble("TEL"));
                            telefono.setDIREC(rs.getString("DIREC"));
                            vTelefonos.add(telefono);
                        }
                    }                    
            }catch(Exception ex){
                JOptionPane.showMessageDialog(null, ex.getMessage(), null, JOptionPane.ERROR_MESSAGE);
            } 
         return vTelefonos;
    }    
        
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnBuscar;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    public javax.swing.ButtonGroup rbgFrecuenciaPago;
    private javax.swing.JTable tbDeudores;
    private javax.swing.JTextField txtCedula;
    private javax.swing.JTextField txtNombre;
    // End of variables declaration//GEN-END:variables
}
